import request from "@/utils/request";
import { useUserStore } from "@/store/modules/user";

/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

/***
 * 不重复随机id
 * @constructor
 */
export function GenNonDuplicateID() {
  let idStr = Date.now().toString(36);
  idStr += Math.random().toString(36).substr(3);
  return idStr;
}

export const downloadFileAndRequest = (
  method: "GET" | "get" | "POST" | "post",
  url: string,
  config: { params?: any; data?: any }
) => {
  let _data = null;
  let _params = null;
  if (method === "GET" || method === "get") {
    _params = config?.params;
  } else {
    _data = config?.data;
  }
  const userStore = useUserStore();
  return request({
    url,
    method,
    params: _params,
    data: _data,
    responseType: "blob",
    headers: {
      // 'X-Token': userStore.token || '',
      Authorization: userStore.token || "",
    },
  })
    .then((res) => {
      console.log(res);
      const str = res.headers["content-disposition"];
      if (!res || !str) {
        ElMessage.error(res.message || "下载失败！");
        return;
      }
      if (res && res.status === 200 && res.data) {
        const { data, headers } = res;
        // // 切割出文件名
        // const fileNameEncode = res.headers['content-disposition'].split('filename=')[1]
        // // 解码
        // const fileName = decodeURIComponent(fileNameEncode)
        // console.log('fileName', fileName)
        let fileName;
        if (headers["content-disposition"]) {
          fileName = headers["content-disposition"].replace(/\w+;filename=(.*)/, "$1");
        } else {
          fileName = data.fileName;
        }
        // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
        const blob = new Blob([data], { type: headers["content-type"] });
        const dom = document.createElement("a");
        const downUrl = window.URL.createObjectURL(blob);
        dom.href = downUrl;
        dom.download = decodeURIComponent(fileName);
        dom.style.display = "none";
        document.body.appendChild(dom);
        dom.click();
        dom.parentNode?.removeChild(dom);
        window.URL.revokeObjectURL(url);
      } else {
        ElMessage.error(res.msg || "下载失败！");
      }
    })
    .catch((err) => {
      console.log("下载失败下载失败下载失败", err);
      ElMessage.error(err || "下载失败！");
    });
};

export function downloadFile(response: any, contentType?: string) {
  contentType = contentType || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
  const blob = new Blob([response.data], {
    type: contentType,
  });
  const a = document.createElement("a");
  const href = window.URL.createObjectURL(blob); // 下载的链接
  a.href = href;
  let title = decodeURI(response.headers["content-disposition"].split(";")[2].split("=")[1].split("''")[1]);
  a.download = title; // 获取后台设置的文件名称
  document.body.appendChild(a);
  a.click(); // 点击导出
  document.body.removeChild(a); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
  ElMessage.success(`${title} 下载成功！`);
}

/**
 * 判断是否移动端
 */
export function isMobile() {
  let flag = navigator.userAgent.match(
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Phone)/i
  );
  return flag;
}
